const https = require('https');
// const cheerio = require('cheerio');
const cheerio = require('cheerio');
const fs = require('fs');
const path = require('path');
// require('stream')

// 要获取的网页 URL
const baseUrl = 'https://www.baiyunu.edu.cn/';
const basePath = path.join(__dirname, 'download');

https.get(baseUrl, (res) => {
    let data = '';

    // 接收数据
    res.on('data', (chunk) => {
        data += chunk;
    });

    // 请求结束后处理数据
    res.on('end', () => {
        console.log(data);
        const $ = cheerio.load(data);

        // 提取所有图片地址
        const imgUrls = [];
        $('img').each((index, element) => {
            let imgUrl = $(element).attr('src');
            // 处理相对地址
            if (imgUrl) {
                imgUrl = new URL(imgUrl, baseUrl).href;  // 生成绝对 URL
                imgUrls.push(imgUrl);
            }
            imgUrls.push(imgUrl);
        });

        // 打印所有图片地址
        console.log('图片地址:');
        imgUrls.forEach((imgUrl, index) => {
            console.log(imgUrl);
            downloadImg(imgUrl, index);
        });
    });

}).on('error', (err) => {
    console.error(`请求错误: ${err.message}`);
});


function downloadImg(url, filename) {
    let ext = url.split('.').pop();
    filename += '.' + ext;
    console.log(`开始下载图片 ${filename}...`);
    https.get(url, (res) => {
        const file = fs.createWriteStream(path.join(basePath, filename));
        res.pipe(file);
        file.on('finish', () => {
            console.log(`图片 ${filename} 下载完成.`);
        });
    }).on('error', (err) => {
        console.error(`图片 ${filename} 下载失败: ${err.message}`);
    });
}
